
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using SqlSugar;
using Util;

namespace API.Controllers
{
    public class UserComputerController : BaseController
    {
        Repository<tUserComputer> _UserComputer;
        Repository<tStaff> _Staff;
        readonly IMapper _mapper;
        public UserComputerController(Repository<tUserComputer> UserComputer, IMapper mapper, Repository<tStaff> staff)
        {
            _UserComputer = UserComputer;
            _mapper = mapper;
            _Staff = staff;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveUserComputerInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tUserComputer>(dto);
                InitEntity(model);
                await _UserComputer.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<UserComputerOutput>>> GetList([FromBody] UserComputerListInput dto)
        {
            ResultMsg<List<UserComputerOutput>> result = new ResultMsg<List<UserComputerOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tUserComputer>();
                //if (!string.IsNullOrWhiteSpace(dto.Name))
                //{
                //    exp.And(x => x.FName.Contains(dto.Name));
                //}
                var list = (await _UserComputer.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var UserComputerOutputs = _mapper.Map<List<UserComputerOutput>>(list);
                return result.Success(UserComputerOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<UserComputerOutput>> GetTheOne(string id)
        {
            ResultMsg<UserComputerOutput> result = new ResultMsg<UserComputerOutput>();
            try
            {
                var model = await _UserComputer.GetByIdAsync(id);
                var dao = _mapper.Map<UserComputerOutput>(model);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _UserComputer.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 上传电脑信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<string>> UploadComputerInfo([FromBody] UploadComputerInfoInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _UserComputer.DeleteAsync(t => t.FComputerId == dto.ComputerId);
                tUserComputer model = new tUserComputer();
                model.FUserID = dto.UserId;
                model.FComputerId = dto.ComputerId;
                model.FSysHostName = dto.SysHostName;
                model.FSystemVer = dto.SystemVer;
                model.FBaseBoard = dto.BaseBoard;
                model.FProcessor = dto.Processor;
                model.FMemory = JsonConvert.SerializeObject(dto.Memory);
                model.FHardDisk = JsonConvert.SerializeObject(dto.HardDisk);
                model.FGraphicsCard = dto.GraphicsCard;
                model.FMonitor = JsonConvert.SerializeObject(dto.Monitor);

                InitEntity(model);
                await _UserComputer.InsertAsync(model);

                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--UploadComputerInfo:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 小程序绑定用户ID和电脑ID
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> BindComputerUser([FromBody] BindComputerUserInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = await _UserComputer.GetFirstAsync(t => t.FUserID == CurrentUserId);
                if(model == null)
                {
                    return result.Error("用户不存在");
                }
                model.FComputerId = dto.ComputerId;
                model.CreateTime = DateTime.Now;
                await _UserComputer.UpdateAsync(model);

                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--BindComputerUser:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取员工列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<List<StaffOutput>>> GetStaffList(StaffInput input)
        {
            ResultMsg<List<StaffOutput>> result = new ResultMsg<List<StaffOutput>>();
            try
            {
                var exp = Expressionable.Create<tStaff>();
                exp.And(t=>!t.FDeleted);
                if (!string.IsNullOrEmpty(input.name))
                {
                    exp.And(t=>t.FUserName.Contains(input.name));
                }
                var list = (await _Staff.GetListAsync(exp.ToExpression())).OrderBy(c => c.FUserName).Select(a => new StaffOutput
                {
                    UserId = a.FUserId,
                    UserName = a.FUserName,
                }).ToList();
                return result.Success(list);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--GetStaffList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 通过用户ID获取唯一
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<UserComputerGetTheOneOutput>> GetTheOneByUserId(string userId)
        {
            ResultMsg<UserComputerGetTheOneOutput> result = new ResultMsg<UserComputerGetTheOneOutput>();
            try
            {
                var model = await _UserComputer.GetFirstAsync(t => t.FUserID == userId);
                if (model == null)
                {
                    return result.Error("找不到该用户的电脑配置信息!");
                }
                UserComputerGetTheOneOutput dao = new UserComputerGetTheOneOutput();
                dao.Id= model.Id;
                dao.UserID = model.FUserID;
                dao.ComputerId = model.FComputerId;
                dao.SysHostName = model.FSysHostName;
                dao.SystemVer = model.FSystemVer;
                dao.BaseBoard = model.FBaseBoard;
                dao.Processor = model.FProcessor;
                dao.GraphicsCard = model.FGraphicsCard;
                dao.Memory =JsonConvert.DeserializeObject<List<string>>(model.FMemory);
                dao.HardDisk = JsonConvert.DeserializeObject<List<string>>(model.FHardDisk);
                dao.Monitor = JsonConvert.DeserializeObject<List<string>>(model.FMonitor);
                dao.CreateTime = model.CreateTime;
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("UserComputerController--GetTheOneByUserId:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
    }
}
